#include "../../native_shm.h"
#include <omp.h>

#include <stdbool.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


int main() {
  // Initializes shm
  native_shm_init_pre_fork();
  char * z = native_shm_malloc(30);
  native_shm_set_global(z);
  srandom(getpid());
  pid_t pid1 = fork();
  pid_t pid2 = fork();
  pid_t pid3 = fork();

  omp_set_num_threads(4);
#pragma omp parallel 
  {
  // Initializes the rest
  native_shm_init_last();



  //Try to malloc something.
  char * ptr = native_shm_malloc(30);
  // Reserve it :
  native_shm_try_acquire( ptr, 30, 0 );
  native_shm_release(ptr);

  

  for ( int i = 0; i < 100000 ; ++ i ) {
    native_shm_blocking_acquire( z, 30, random()%2==0?false:true );
//      printf("Acquire success %d! (%d,%d)\n",i,getpid(), omp_get_thread_num() );
    native_shm_release(z);

  }
  
  // Free it
  native_shm_free(ptr);

  

  }

  if ( pid1 ) {
    waitpid( pid1, NULL,0 );
  }
  if ( pid2 ) {
    waitpid( pid2, NULL,0 );
  }
  if ( pid3 ) {
    waitpid( pid3, NULL,0 );
  }

}
